package com.example.carrierapp.ui.main.dispatch.search

import android.app.Activity
import android.content.Intent
import android.support.v7.widget.LinearLayoutManager
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.View
import com.example.carrierapp.base.MVPBaseActivity
import com.example.carrierapp.config.ConstValue
import com.example.carrierapp.config.toast
import com.example.carrierapp.ui.adapter.CommonRecyclerAdapter
import com.example.carrierapp.ui.view.recycleview.HorizontalDividerDecoration
import com.example.carrierapp.ui.view.recycleview.WrapContentManager
import com.example.carrierapp.ui.view.recycleview.XRecyclerView
import com.example.carrierapp.util.*
import com.example.carrierapp.viewmodel.itemmodel.ItemSearchModel
import com.example.lb.fingerdemo.R
import com.google.gson.Gson
import kotlinx.android.synthetic.main.activity_dispatch_search.*
import kotlinx.android.synthetic.main.layout_recycleview.*
import kotlinx.android.synthetic.main.layout_search_bar.*

class DispatchSearchActivity : MVPBaseActivity<DispatchSearchContract.View, DispatchSearchPresenter>(), DispatchSearchContract.View, XRecyclerView.LoadingListener {
    private var mSearchType = SEARCH_TYPE_CARNUM

    private val adapter by lazy {
        CommonRecyclerAdapter<ItemSearchModel>(this, R.layout.item_dispatch_search_new) { v, _, i ->
            v.setOnClickListener {
                refreshChecked(i)
            }
        }
    }

    override fun getContentView() = R.layout.activity_dispatch_search

    override fun getTitleString(): String? {
        return null
    }

    private fun refreshChecked(i: Int) {
        adapter.data?.forEachIndexed { index, itemSearchModel ->
            itemSearchModel.checked = i == index
        }
        adapter.notifyDataSetChanged()
    }

    override fun createPresenter(): DispatchSearchPresenter {
        return DispatchSearchPresenter(this)
    }

    override fun showBottomLine(): Boolean {
        return false
    }

    override fun initData() {
        mSearchType = intent.getIntExtra(ConstValue.TYPE, SEARCH_TYPE_DRIVER)
    }

    override fun initView() {

        when (mSearchType) {
            SEARCH_TYPE_DRIVER -> {
                titleString = "选择驾驶员"
                et_dispatch_search.hint = "姓名/电话"
                notice_view.text = "禁运的驾驶员无法被搜索和调度！"
            }
            SEARCH_TYPE_CARNUM -> {
                titleString = "搜索车牌"
                notice_view.text = "禁运的车辆无法被搜索和调度！"
                et_dispatch_search.hint = "请输入车牌号"
            }
        }
        initRecycleView()
    }

    override fun initEvent() {
        save.setOnClickListener {
            adapter.find { it.checked }?.let {
                val intent = Intent()
                intent.putExtra("info", Gson().toJson(it))
                setResult(Activity.RESULT_OK, intent)
                finish()
            } ?: let {
                val input = et_dispatch_search.text.toString()
                if (mSearchType == SEARCH_TYPE_CARNUM)
                    if (RegUtil.isCarNumber(input).not()) {
                        ToastUtils.showCenterToast(this, "请输入正确的车牌号")
                        return@setOnClickListener
                    }
                val result = ItemSearchModel()
                result.name = input
                val intent = Intent()
                intent.putExtra("info", Gson().toJson(result))
                setResult(Activity.RESULT_OK, intent)
                finish()
            }
        }
        et_dispatch_search.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
                if (!TextUtils.isEmpty(et_dispatch_search.text.toString().trim { it <= ' ' })) {
                    ib_clear.visibility = View.VISIBLE
                } else {
                    ib_clear.visibility = View.GONE
                }
                val filter = et_dispatch_search.text.toString().trim { it <= ' ' }
                when (mSearchType) {
                    SEARCH_TYPE_CARNUM -> mPresenter.getCarNumList(filter)
                    SEARCH_TYPE_DRIVER -> mPresenter.getDriverList(filter)
                }
            }

            override fun afterTextChanged(s: Editable) {

            }
        })
        ib_clear.setOnClickListener { et_dispatch_search.setText("") }
    }

    private fun initRecycleView() {
        val mLinearLayoutManager = WrapContentManager(this, LinearLayoutManager.VERTICAL, false)
        recycler_view.layoutManager = mLinearLayoutManager
        recycler_view.addItemDecoration(HorizontalDividerDecoration(this, R.drawable.divider_horizontal_2_f3f6fa, DisplayUtil.dip2px(this, 2f)))
        recycler_view.setHasFixedSize(true)
        recycler_view.setLoadingMoreEnabled(false)
        recycler_view.setPullRefreshEnabled(true)
        recycler_view.adapter = adapter
    }

    override fun onSearchError(msg: String) {
        dismissProgress()
        LogUtil.d("DispatchSearchActivity-getDriverListFailed-$msg")
        ToastUtils.showCenterToast(msg, this)
        recycler_view.refreshComplete()
        ll_empty.visibility = if (adapter.itemCount == 0) View.VISIBLE else View.GONE
    }

    override fun onSearchSucess(bean: MutableList<ItemSearchModel>) {
        dismissProgress()
        LogUtil.d("DispatchSearchActivity-getCarNumListFailed-$bean")
        recycler_view.refreshComplete()
        if (!ConnectionUtil.isNull(bean)) {
            ll_empty.visibility = View.GONE
            adapter.refresh(bean)
            recycler_view.setNoMore(bean.size < 30)
        } else {
            recycler_view.setNoMore(true)
            adapter.clear()
            ll_empty.visibility = View.VISIBLE
        }
    }

    override fun onRefresh() {
        val filter = et_dispatch_search.text.toString().trim { it <= ' ' }
        showProgress()
        when (mSearchType) {
            SEARCH_TYPE_CARNUM -> mPresenter.getCarNumList(filter)
            SEARCH_TYPE_DRIVER -> mPresenter.getDriverList(filter)
        }
    }

    override fun onLoadMore() {

    }

    companion object {
        const val SEARCH_TYPE_DRIVER = 0
        const val SEARCH_TYPE_CARNUM = 1
    }
}
